package com.analysis.utils;

import com.analysis.entity.Question;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 问题Excel导出工具类
 */
public class QuestionExcelExportUtils {
    
    // Excel列标题
    private static final String[] HEADERS = {
         "产品名称", "问题内容", "竞争对手名称", "创建时间", "修改时间"
    };
    
    // 列宽度
    private static final int[] COLUMN_WIDTHS = {
        50, 150, 50, 40, 40
    };
    
    /**
     * 导出问题数据到Excel
     * 
     * @param questions 问题列表
     * @param sheetName 工作表名称
     * @return Excel文件的字节数组
     * @throws IOException IO异常
     */
    public static byte[] exportQuestionsToExcel(List<Question> questions, String sheetName) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建工作表
            Sheet sheet = workbook.createSheet(sheetName);
            
            // 创建样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            CellStyle dataStyle = createDataStyle(workbook);
            CellStyle dateStyle = createDateStyle(workbook);
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < HEADERS.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(HEADERS[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, COLUMN_WIDTHS[i] * 256);
            }
            
            // 填充数据
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < questions.size(); i++) {
                Question question = questions.get(i);
                Row row = sheet.createRow(i + 1);

                // 产品名称
                createCell(row, 0, question.getProductName(), dataStyle);
                
                // 问题内容
                createCell(row, 1, question.getQuestion(), dataStyle);
                
                // 竞争对手名称
                createCell(row, 2, question.getCompetitorName(), dataStyle);
                
                // 创建时间
                if (question.getCreated() != null) {
                    createCell(row, 3, question.getCreated().format(dateFormatter), dateStyle);
                } else {
                    createCell(row, 3, "", dataStyle);
                }
                // 修改时间
                if (question.getModified() != null) {
                    createCell(row, 4, question.getModified().format(dateFormatter), dateStyle);
                } else {
                    createCell(row, 4, "", dataStyle);
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < HEADERS.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
    
    /**
     * 创建标题样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
    
    /**
     * 创建数据样式
     */
    private static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);
        return style;
    }
    
    /**
     * 创建日期样式
     */
    private static CellStyle createDateStyle(Workbook workbook) {
        CellStyle style = createDataStyle(workbook);
        style.setAlignment(HorizontalAlignment.CENTER);
        return style;
    }
    
    /**
     * 创建单元格
     */
    private static void createCell(Row row, int columnIndex, Object value, CellStyle style) {
        Cell cell = row.createCell(columnIndex);
        if (value != null) {
            cell.setCellValue(value.toString());
        } else {
            cell.setCellValue("");
        }
        cell.setCellStyle(style);
    }
    
    /**
     * 生成文件名
     * 
     * @param prefix 文件名前缀
     * @return 文件名
     */
    public static String generateFileName(String prefix) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
        return prefix + "_" + LocalDateTime.now().format(dateFormatter) + ".xlsx";
    }
}
